class User < ActiveRecord::Base
  has_many :user_settings, :dependent => :destroy
  
  validates_presence_of     :name, :message => "请输入用户姓名"
  validates_uniqueness_of   :name, :message => "已经存在同名用户，请输入另一个名字"
  validates_presence_of     :username, :message => "请输入帐号"
  validates_uniqueness_of   :username, :message => "已经存在同名帐号，请输入另一个帐号"
  validates_confirmation_of :password, :message => "两次输入的密码不一致，请核对后重新输入"
  validates_presence_of     :permission, :message => "请选择权限"
  
  attr_accessor :password_confirmation
  
  def validate
    errors.add_to_base("请设置密码。") if hashed_password.blank?
  end
  
  def self.authenticate(username, password)
    user = self.find_by_username(username)
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end
  
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    create_new_salt
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  def after_destroy
    if User.count.zero?
      raise "不能删除最后一个用户。"
    end
  end     
  
  def get_setting(name)
    user_setting = user_settings.find_by_name(name)
    return user_setting.nil? ? nil : user_setting.value
  end
  
  def set_setting(name, value)
    setting = user_settings.find_by_name(name)
    if setting.nil?
      user_settings.create(:name => name, :value => value)
    else
      setting.value = value
      setting.save
    end
  end
  
  private
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "enjoy" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
end
